<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="停车场名称">
              <el-input v-model="formInline.name"></el-input>
            </el-form-item>
            <el-form-item label="停车场地址">
              <el-input v-model="formInline.address"></el-input>
            </el-form-item>
            <el-form-item label="地理位置纬度">
              <el-input v-model="formInline.latitude"></el-input>
            </el-form-item>
            <el-form-item label="地理位置经度">
              <el-input v-model="formInline.longitude"></el-input>
            </el-form-item>
            <el-form-item label="营业时间">
              <el-input v-model="formInline.operatingHours"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="formInline.phone"></el-input>
            </el-form-item>
            <el-form-item label="收费策略编号">
              <el-input v-model="formInline.feeScheduleCode"></el-input>
            </el-form-item>
            <el-form-item label="停车场描述">
              <el-input v-model="formInline.description"></el-input>
            </el-form-item>
            <el-form-item label="停车场编号">
              <el-input v-model="formInline.code"></el-input>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-config-provider :locale="locale">
                <el-date-picker
                  v-model="formInline.createTime"
                  type="date"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :locale="locale"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item label="修改时间">
              <el-config-provider :locale="locale">
                <el-date-picker
                  v-model="formInline.updateTime"
                  type="date"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :locale="locale"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button type="info" @click="resetQueryData">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-loading="isLoading" element-loading-text="加载中...">
          <el-form-item style="float: right;">
              <el-button type="success" @click="showAddDialog = true">新增</el-button>
              <el-button type="warning" @click="handleBatchDelete" >批量删除</el-button>
              <el-button type="danger" @click="deleteAll" >清空数据</el-button>
            </el-form-item>
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="70" align="center" style = "background-color :black">
              <template #default="scope">
                <div class="serial-number">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="停车场id" v-if="false"></el-table-column>
            <el-table-column prop="code" label="停车场编号" width="100"></el-table-column>
            <el-table-column prop="name" label="停车场名称" width="100"></el-table-column>
            <el-table-column prop="address" label="停车场地址" width="200"></el-table-column>
            <el-table-column prop="operatingHours" label="营业时间" width="180"></el-table-column>
            <el-table-column prop="phone" label="联系电话" width="100"></el-table-column>
            <el-table-column prop="feeScheduleCode" label="收费策略编号" width="120"></el-table-column>
            <el-table-column prop="description" label="停车场描述" width="220"></el-table-column>
            <el-table-column prop="latitude" label="地理位置纬度" width="150"></el-table-column>
            <el-table-column prop="longitude" label="地理位置经度" width="150"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
            <el-table-column prop="updateTime" label="修改时间" width="180"></el-table-column>
            <el-table-column width="200" label="操作">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
                <el-button size="small" type="danger" @click="handleDelete([scope.row.id])">删除</el-button>
                <el-tooltip 
                  class="box-item" 
                  effect="dark" 
                  :content="`总车位数：${scope.row.TotalSpaces}; 可用车位数: ${scope.row.AvailableSpaces}`" 
                  placement="top"
                >
                <a href="javascript:void(0);" class="underline-link" @mouseover="showTooltip = true" @mouseleave="showTooltip = false" style = "margin-left : 10px">详情</a> 
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px; margin-bottom: 20px; text-align: right; float: right;">
            <el-config-provider :locale="locale">
              <el-pagination
                background
                class="pagination"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              ></el-pagination>
            </el-config-provider>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 引入新增停车场对话框组件 -->
    <AddParkingDialog 
      :visible="showAddDialog" 
      @update:visible="showAddDialog = $event"
      @add="handleAdd"
    />
    <EditParkingDialog 
      :visible="showEditDialog" 
      :parkingLotId="updateParkingLotId"
      :updateName="updateName"
      :updateAddress="updateAddress"
      :updateLatitude="updateLatitude"
      :updateLongitude="updateLongitude"
      :updateOperatingHours="updateOperatingHours"
      :updatePhone="updatePhone"
      :updateFeeScheduleCode="updateFeeScheduleCode"
      :updateDescription="updateDescription"
      :updateCode="updateCode"
      @update:visible="showEditDialog = $event"
      @edit="fetchData"
    />
  </div>
</template>
<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn'; 
import { ref, watch } from 'vue';
import axios from 'axios';
import AddParkingDialog from '@/components/AddParkingDialog.vue';
import EditParkingDialog from '@/components/EditParkingDialog.vue';
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRoute } from 'vue-router';

const route = useRoute();
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const updateParkingLotId = ref(0);
const updateName = ref('');
const updateAddress= ref('');
const updateLatitude= ref('');
const updateLongitude= ref('');
const updateOperatingHours= ref('');
const updatePhone = ref('');
const updateFeeScheduleCode= ref('');
const updateDescription= ref('');
const updateCode = ref('');

const formInline = ref({
  id: '',
  name: '',
  address: '',
  latitude: '',
  longitude: '',
  operatingHours: '',
  phone: '',
  feeScheduleCode: '',
  description: '',
  createTime: null,
  updateTime: null,
  code: ''
});
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const locale = zhCn;
const isLoading = ref(false);
const selectedIds = ref([]);

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}`
    }
})

// 监听路由变化, 避免在其他页面修改影响本页面数据时不自动刷新的情况
watch(() => route.path, (newPath) => {
  if(newPath === '/admin/ParkingManagement') {
    console.error("刷新ParkingManagement");
    fetchData();
  }
});
const fetchData = async () => {
  isLoading.value = true;
  const params = {
    ...formInline.value,
    pageIndex: currentPage.value,
    pageSize: pageSize.value
  };
  Object.keys(params).forEach(key => (params[key] === '' || params[key] === null) && delete params[key]);
  if ('code' in params && params.code) {
    params.lotCode = params.code;
    delete params.code;
  }
  try {
    const response = await api.get('/api/v1/parking-lot/parking-lot-info', { params });
    if (response.data.code === "200") {
        if(response.data.data != null){
          let records = response.data.data.records;
          const promises = records.map(record => 
                  fetchTotalAndAvailableSpaces(record.code)
                      .then(spaces => ({ ...record, ...spaces }))
              );
          tableData.value = await Promise.all(promises);
          total.value = response.data.data.total;
        } else {
          tableData.value = [];
          total.value = 0;
        }
      } else {
        ElMessage({
          title: '错误',
          message: '获取停车场记录失败！' + response.data.message,
          type: 'error',
          showClose: false
        });
      }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '获取停车场记录失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    isLoading.value = false;
  }
};
const fetchTotalAndAvailableSpaces = async (parkingLotCode) => {
  // 使用 params 选项来指定查询参数
  const params = new URLSearchParams({
      lotCode: parkingLotCode
  });

  try {
      const response = await api.get('/api/v1/parking-space/parking-space-available', { 
          params: params 
      });
      if (response.data.code === "200") {
          return {
              TotalSpaces: response.data.data.totalSpaces,
              AvailableSpaces: response.data.data.availableSpaces
          };
        } else {
          console.error('获取可用车位信息失败！' + response.data.message);
        }
    } catch (error) {
      console.error('获取可用车位信息失败！' + error.message);
      return { TotalSpaces: 0, AvailableSpaces: 0 };
    }
};

const handleAdd = async () => {
  await fetchData();
};
const handleEdit = async (row) => {
  updateParkingLotId.value = row.id;
  updateName.value = row.name;
  updateAddress.value = row.address;
  updateLatitude.value = row.latitude;
  updateLongitude.value = row.longitude;
  updateOperatingHours.value = row.operatingHours;
  updatePhone.value = row.phone;
  updateFeeScheduleCode.value = row.feeScheduleCode;
  updateDescription.value = row.description;
  updateCode.value = row.code;
  showEditDialog.value = true;
};
const handleDelete = async (ids) => {
  try {
    const response = await api.delete('/api/v1/parking-lot/parking-lot-info', {
       data: { ids }
    });
    if (response.data.code === "200") {
      ElMessage({
        title: '成功',
        message: '删除成功',
        type: 'success',
        showClose: false
      });
      selectedIds.value = [];
    } else {
      ElMessage({
        title: '错误',
        message: '删除失败！' + response.data.message,
        type: 'error',
        showClose: false
      });
    }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '删除失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    await fetchData();
    isLoading.value = false;
  }
};
const handleBatchDelete = async () => {
  handleDelete(selectedIds.value);
}
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};
const handleCurrentChange = (page) => {
  currentPage.value = page;
  console.error("页数发生变化:" + page)
  fetchData();
};
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchData();
};
const deleteAll = async () => {
  ElMessageBox.confirm(
    '此操作将永久删除所有数据, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    isLoading.value = true;
    try {
      const response = await api.delete('/api/v1/parking-lot/all-parking-lot-info');
      if (response.data.code === "200") {
        ElMessage({
          title: '成功',
          message: '所有数据删除成功',
          type: 'success',
          showClose: false,
        });
        tableData.value = [];
      } else {
        ElMessage({
          title: '错误',
          message: '删除失败！' + response.data.message,
          type: 'error',
        });
      }
    } catch (error) {
      ElMessage({
        title: '错误',
        message: '删除失败！' + error.message,
        type: 'error',
      });
    } finally {
      isLoading.value = false;
      fetchData();
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}
const resetQueryData = () =>{
  formInline.value = {
    id: '',
    name: '',
    address: '',
    latitude: '',
    longitude: '',
    operatingHours: '',
    phone: '',
    feeScheduleCode: '',
    description: '',
    createTime: null,
    updateTime: null,
    code: ''
  };
  fetchData();
}

fetchData();
</script>

<style scoped>
.admin-dashboard {
  height: 100vh;
}
.el-container {
  height: 100%;
}
.el-aside {
  background-color: #f8f9fa;
}
.el-main {
  padding: 20px;
}
.el-card {
  margin-bottom: 20px; /* 卡片底部外边距 */
}
.el-table .cell {
  pointer-events: none;
}
.pagination {
  margin: 2rem auto;
  display: flex;
  justify-content: center;
}
</style>